package com.example.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import com.example.demo.service.BookService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class BookServiceImpl implements BookService {

    @Resource
    BookMapper bookMapper;

    @Override
    public IPage<Book> selectPage(Integer pageNum, Integer pageSize, String name, String author) {
        QueryWrapper<Book> queryWrapper =  new QueryWrapper<>();
        Page<Book> page = new Page<>(pageNum,pageSize);
        if (StrUtil.isNotBlank(name)){
            queryWrapper.lambda().like(Book::getName,name);
        }
        if (StrUtil.isNotBlank(author)){
            queryWrapper.lambda().like(Book::getAuthor,author);
        }
        return bookMapper.selectPage(page,queryWrapper);
    }

    @Override
    public Result<?> addBook(Book book) {
        book.setCreateTime(new Date());
        book.setDeleted(0);
        bookMapper.insert(book);
        return Result.success();
    }

    @Override
    public Result<?> updateBook(Book book) {
        bookMapper.updateById(book);
        return Result.success();
    }

    @Override
    public Result<?> deleteBook(int bookId) {
        bookMapper.deleteById(bookId);
        return Result.success();
    }

    @Override
    public IPage<Book> selectBookByUserId(Integer pageNum, Integer pageSize, Integer userId) {
        Page<Book> page = new Page<>(pageNum,pageSize);
        return bookMapper.selectBookByUserId(page,userId);
    }
}
